/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.toools.gwt.wmc.server.dao.toplink;

import java.util.Collection;
import javax.persistence.NoResultException;
import oracle.toplink.essentials.ejb.cmp3.EntityManager;
import oracle.toplink.essentials.expressions.Expression;
import oracle.toplink.essentials.expressions.ExpressionBuilder;
import org.springframework.stereotype.Repository;
import org.toools.gwt.wmc.jpa.Account;
import org.toools.gwt.wmc.server.dao.IAdditiveDAO;
import org.toools.gwt.wmc.jpa.Additive;

/**
 *
 * @author ich
 */
@Repository
public class AdditiveDAO implements IAdditiveDAO{

//    @PersistenceContext
//    public void setEntityManager( EntityManager em) {
//        this.em = em;
//    }

    public Additive getAdditiveByID(Integer id) {
        Additive result;
        try {
//            EntityManagerFactory emf = Persistence.createEntityManagerFactory("blabla");
//            emf.createEntityManager();
            result = (Additive) EMFKeeper.EM.createNamedQuery("Additive.getById").setParameter("id", id).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
        System.out.println("fetched additive " + result.getId() + " from db.");
        return result;
    }

    public Boolean belongsTo( Integer id, Integer accountid ) {
        //muessen alle companyparts dazugehoeren??

        EntityManager em = (EntityManager)EMFKeeper.EM;
        ExpressionBuilder eb = new ExpressionBuilder();
        Expression additive = eb.get( "id" ).equal( id );
        Expression belongsto = additive.anyOf( "comopanyParts" ).anyOf( "companie" ).get( "account" ).get( "id" ).equal( accountid );

        return em.getSession().readAllObjects( Account.class, belongsto ).size() > 0;
    }

    public Collection<Additive> getAdditives() {
        Collection<Additive> ret = EMFKeeper.EM.createNamedQuery("Additive.getAll").getResultList();

        System.out.println("fetched " + ret.size() + " additives from db.");
        return ret;
    }

    public Collection<Additive> getAdditives(Integer accountid) {
        EntityManager em = (EntityManager)EMFKeeper.EM;

        ExpressionBuilder eb = new ExpressionBuilder();
        Expression accadditives = eb.anyOf( "companyParts" ).anyOf( "companie" ).get( "account" ).get( "id" ).equal( accountid );

        Collection<Additive> ret = em.getSession().readAllObjects( Additive.class, accadditives );
        return ret;
    }

    public Additive create(Additive a) {
        return SimpleCUD.create( a );
    }

    public Boolean delete(Additive a) {
        Additive rem = (Additive) EMFKeeper.EM.createNamedQuery( "Additive.getById" ).setParameter( "id", a.getId() ).getSingleResult();
        return SimpleCUD.delete( rem );
    }

    public Boolean update(Additive a) {
        return SimpleCUD.update( a );
    }
}
